#include "NetworkCommonFunction.h"
#include "playstoredfile.h"
#include "pathconst.h"

#include <boost/scoped_array.hpp>
#include <QDomDocument>
#include <QFile>
#include <QDebug>

bool PlayStoreFileHandler(int socket, int commandLength)
{
	qDebug()<<"Recieved play stored video file command";

	unsigned long fileInfoXmlLength;
	if(!getFourByte(socket, fileInfoXmlLength))
	{
		qDebug()<<"Get file info xml length error";
		return false;
	}

	char* xmlBuffer = new char[fileInfoXmlLength];
	boost::scoped_array<char> xmlBufferContainer(xmlBuffer);

	if(!receiveData(socket, xmlBuffer, fileInfoXmlLength))
	{
		qDebug()<<"Get file info xml error";
		return false;
	}

	QDomDocument domDocument;
	domDocument.setContent(QByteArray(xmlBuffer, fileInfoXmlLength));

	QDomElement rootElement = domDocument.firstChildElement();
	int windowNo = rootElement.attribute("WindowNo").toInt();

	QString playListPath = PlayListPath(windowNo);
	QFile file(playListPath);
	if(!file.open(QFile::WriteOnly))
	{
		qDebug()<<"Open play list file to write error";
		//ignore this error
	}
	else
	{
		QTextStream stream(&file);
		domDocument.save( stream, 4);
	}
	file.close();

	PlayStoredFile playStoredFile(playListPath);
	playStoredFile.doCommand();

	return true;
}
